package com.lagou.edu.filter;


import com.lagou.edu.FeginClient.UserFeginClient;
import com.lagou.edu.utils.RedisUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Component
@Slf4j
public class GateWatFilter implements GlobalFilter, Ordered {



    @Value("${lagou.times}")
    private int times;
    @Value("${lagou.second}")
    private int second;

    Map<String,RequestStrategy> explosionMap = new HashMap<>();
    private static List<String> blackList = new ArrayList<>();

    @Autowired
    private UserFeginClient userFeginClient;


    @Autowired
    RedisUtils redisUtils;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //开始时间
        long startTime = System.currentTimeMillis();

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String clientIp = request.getRemoteAddress().getHostString();
        String requestPath = request.getPath().toString();


        MultiValueMap<String, HttpCookie> cookieMultiValueMap =  request.getCookies();
        HttpCookie cookie = cookieMultiValueMap.getFirst("token");


        if(requestPath.indexOf("/user/login") == -1 && cookie != null &&
                redisUtils.get(cookie.getValue()) == null){
            String url = "http://www.test.com/static/login.html";
            //303状态码表示由于请求对应的资源存在着另一个URI，应使用GET方法定向获取请求的资源
            System.out.printf("303状态码表示由于请求对应的资源存在着另一个URI ");
            response.setStatusCode(HttpStatus.SEE_OTHER);
            response.getHeaders().set(HttpHeaders.LOCATION, url);
            return response.setComplete();
        }
        if(requestPath.indexOf("/code/create") != -1){
            long size = redisUtils.lGetListSize(clientIp);
            if(size > times){
                if(startTime - Long.valueOf(redisUtils.lGetIndex(clientIp,0).toString()) > second * 1000){
                    System.out.println(startTime);
                    System.out.println(redisUtils.lGetIndex(clientIp,0).toString());
                    System.out.println(startTime - Long.valueOf(redisUtils.lGetIndex(clientIp,0).toString()) -second * 1000);

                    redisUtils.lRemoveLeftFisrt(clientIp);
                    redisUtils.lSet(clientIp,startTime);
                }else {
                    System.out.println("IP:" + clientIp  + "访问过于频繁");
                    String data = "访问过于频繁，请稍后从试";
                    DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                    return response.writeWith(Mono.just(wrap));
                }

            }else {
                redisUtils.lSet(clientIp,startTime);
            }
        }

        //合法请求
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }


    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class RequestStrategy {

        private long starttime;//IP最先请求时间
        private long endtime;  //IP最后请求时间
        private int count;    //请求次数

    }
}



